package edu.ucsb.android.APMap;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Environment;
import android.util.Log;

public class FileOP {
	
	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;
	
	private FileOP(){
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    // We can read and write the media
		    mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    // We can only read the media
		    mExternalStorageAvailable = true;
		    mExternalStorageWriteable = false;
		} else {
		    // Something else is wrong. It may be one of many other states, but all we need
		    //  to know is we can neither read nor write
		    mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
	}
	
	public static FileOP getFileOP(){
		FileOP fileHandler = new FileOP();
		return fileHandler;
	}
	
	public boolean writeToFile(String content){
		try {
			if (mExternalStorageWriteable){
				File sdRoot = Environment.getExternalStorageDirectory();
			    
		        File file = new File(sdRoot, genFileName());
		        FileWriter gpxwriter = new FileWriter(file, true);
		        BufferedWriter out = new BufferedWriter(gpxwriter);
		        out.write(content);
		        out.close();
		        Log.d("FILE writer", "######## successful write to file");
		        return true;
		    }
			Log.d("FILE writer", "######## external storage is not writable");
			return false;
		} catch (IOException e) {
		    Log.e("FILE Writer", "########### Could not write file " + e.getMessage());
		    return false;
		}
	}
	
	private String genFileName(){
		SimpleDateFormat dataFormat = new SimpleDateFormat("MM-dd-hh");
		String dateInfo = dataFormat.format(new Date());
		return "ap-" + dateInfo + ".txt";
	}
}
